package com.mornd.gulimall.coupon.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mornd.gulimall.common.core.exception.ServiceException;
import com.mornd.gulimall.common.core.result.AjaxResult;
import com.mornd.gulimall.common.core.validation.UpdateGroup;
import com.mornd.gulimall.coupon.entity.SeckillSession;
import com.mornd.gulimall.coupon.service.ISeckillSessionService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * <p>
 * 秒杀活动场次 前端控制器
 * </p>
 *
 * @author mornd
 * @since 2023-08-05
 */
@RestController
@RequestMapping("/coupon/seckillSession")
public class SeckillSessionController {
    @Resource
    private ISeckillSessionService service;

    @GetMapping
    public AjaxResult pageList(SeckillSession session) {
        IPage<SeckillSession> result = service.pageList(session);
        return AjaxResult.success(result);
    }

    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Long id) {
        return AjaxResult.success(service.getById(id));
    }

    @GetMapping("/all")
    public AjaxResult all() {
        return AjaxResult.success(service.list());
    }

    @PutMapping
    public AjaxResult save(@RequestBody @Validated SeckillSession seckillSession) {
        if(LocalDateTime.now().isAfter(seckillSession.getStartTime())) {
            throw new ServiceException("开始时间需晚于当前时间");
        }
        if (seckillSession.getStartTime().isAfter(seckillSession.getEndTime())) {
            throw new ServiceException("开始时间需早于结束时间");
        }
        seckillSession.setId(null);
        seckillSession.setCreateTime(LocalDateTime.now());
        service.save(seckillSession);
        return AjaxResult.success();
    }

    @PostMapping
    public AjaxResult update(@RequestBody @Validated(UpdateGroup.class)
                             SeckillSession seckillSession) {
        if(LocalDateTime.now().isAfter(seckillSession.getStartTime())) {
            throw new ServiceException("开始时间需晚于当前时间");
        }
        if (seckillSession.getStartTime().isAfter(seckillSession.getEndTime())) {
            throw new ServiceException("开始时间需早于结束时间");
        }
        service.updateById(seckillSession);
        return AjaxResult.success();
    }

    @DeleteMapping("/{ids}")
    public AjaxResult delete(@PathVariable("ids") Long[] ids) {
        service.removeByIds(Arrays.asList(ids));
        return AjaxResult.success();
    }
}
